package com.drakulo.games.ais.core.delayed;

import java.math.BigDecimal;

import com.drakulo.games.ais.core.NumberHelper;

/**
 * A delayed action is an action wich take time to be done.
 * 
 * @author Drakulo
 * 
 */
public abstract class DelayedAction {
	/** The steps */
	private int count;
	/** The action duration in seconds */
	private int duration;
	/** set to true if the action is done */
	private boolean done;
	/** The number of construction robots used by the action */
	private int robotsUsed;
	/** Callback */
	private Runnable callback;

	/**
	 * Constructor
	 * 
	 * @param duration
	 *            the action duration in seconds
	 * @param robotsUsed
	 *            the number of construction robots needed
	 */
	protected DelayedAction(int duration, int robotsUsed) {
		this.count = 0;
		this.duration = duration;
		this.done = false;
		this.robotsUsed = robotsUsed;
	}

	/**
	 * Step the action
	 */
	public void step() {
		this.count++;
		if (this.count > this.duration) {
			this.done = true;
		}
	}

	/**
	 * @return true if the action is done
	 */
	public boolean isDone() {
		return this.done;
	}

	/**
	 * @return the number of robots used during the action
	 */
	public int getRobotsUsed() {
		return this.robotsUsed;
	}

	/**
	 * @return the action progression in percents
	 */
	public int getProgression() {
		BigDecimal currentTime = BigDecimal.valueOf(this.count);
		BigDecimal endTime = BigDecimal.valueOf(this.duration);

		int percentage = NumberHelper.getPercentage(endTime, currentTime)
				.intValue();

		if (percentage > 100) {
			percentage = 100;
		}
		return percentage;
	}

	public int getDuration() {
		return this.duration;
	}

	public int getCurrentValue() {
		return this.count;
	}

	public void setCallback(Runnable callback) {
		this.callback = callback;
	}

	protected Runnable getCallback() {
		return this.callback;
	}

	/**
	 * Runs the callback method if defined
	 */
	public void runCallback() {
		if (this.callback != null) {
			this.callback.run();
		}
	}
}
